package com.farm.common.security;

import cn.hutool.json.JSONUtil;
import com.farm.common.constant.CommonConstants;
import com.farm.common.util.R;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class SecurityServletResponse {
    public static void responseProcessing(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, R<String> result, Integer status){
        result.setCode(CommonConstants.FAIL);

        // 允许跨域
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        // 允许自定义请求头token(允许head跨域)
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Authorization, authorization,token, from,Accept, Origin, X-Requested-With, Content-Type, Last-Modified");
        httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8");
        httpServletResponse.setStatus(status);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        String resBody = JSONUtil.toJsonStr(result);
        try{
            PrintWriter writer = httpServletResponse.getWriter();
            writer.print(resBody);
            writer.flush();
            writer.close();
        }catch (Exception ignored){}
    }
}
